<?php
namespace App\Services;
use Exception;
use Illuminate\Support\Facades\Cache;
use EasyWeChat\Factory;
use GuzzleHttp\Client;
use Config,Log;

class MiniappService
{
    public static function getMiniappCode($appid,$path,$other_id)
    {
        $miniapp = Config::get("miniapps.".$appid);
        $app = Factory::miniProgram($miniapp);
        $response = $app->app_code->get($path);
        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            $filename = $response->saveAs(public_path("/miniapps"), $other_id.'.png');
        }
        $currentPageUrl = 'http';
        if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") {
            $currentPageUrl .= "s";
        }
        $currentPageUrl .= "://";
        $currentPageUrl .= $_SERVER["SERVER_NAME"];
        return $currentPageUrl."/miniapps/".$other_id.'.png';
    }

    public static function code2Session($js_code,$appid,$secret)
    {
        $client = new Client;
        $response = $client->request('GET', 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$secret.'&js_code='.$js_code.'&grant_type=authorization_code');
        $body = $response->getBody();
        return json_decode($body,true);
    }

    public static function getAccessToken($appid)
    {
        $miniapp = Config::get("miniapps.".$appid);
        if (empty($miniapp)) {
            return ["status"=>"error","msg"=>"小程序不存在!","accessToken"=>""];
        }
        $accessToken = Cache::get('accessToken_'.$appid);
        if (empty($accessToken)) {
            $client = new Client;
            $response = $client->request('GET', 'https://api.weixin.qq.com/cgi-bin/token?appid='.$miniapp["app_id"].'&secret='.$miniapp["secret"].'&grant_type=client_credential');
            $body = $response->getBody();
            $result = json_decode($body,true);
            if (!isset($result["access_token"])) return ["status"=>"error","msg"=>"获取AccessToken失败!","accessToken"=>""];
            $accessToken = $result["access_token"];
            Cache::put('accessToken_'.$appid,$accessToken,7100);
        }
        return ["status"=>"success","msg"=>"","access_token"=>$accessToken];
    }

    public static function msgSecCheck($access_token,$content,$openid)
    {
        $client = new Client;
        $response = $client->post('https://api.weixin.qq.com/wxa/msg_sec_check', [
            'query' => [
                "access_token" => $access_token,
            ],
            'body' => json_encode([
                'content' => $content,
                'version' => 2,
                'openid' => $openid,
                'scene' => 4
            ], JSON_UNESCAPED_UNICODE),
        ]);
        $body = $response->getBody();
        $result = json_decode($body,true);
        if ($result["errcode"] != 0) return true;
        if (in_array($result["result"]["label"],[100,10001])) {
            return true;
        } else {
            return false;
        }
    }

    public static function getUserPhoneNumber($access_token,$code,$openid)
    {
        $client = new Client;
        $response = $client->post('https://api.weixin.qq.com/wxa/business/getuserphonenumber', [
            'query' => [
                "access_token" => $access_token,
            ],
            'body' => json_encode([
                'code' => $code,
                'openid' => $openid,
            ], JSON_UNESCAPED_UNICODE),
        ]);
        $body = $response->getBody();
        $result = json_decode($body,true);
        return $result;
    }

    public static function getWxaCode($access_token,$path)
    {
        $client = new Client;
        $response = $client->post('https://api.weixin.qq.com/wxa/getwxacode', [
            'query' => [
                "access_token" => $access_token,
            ],
            'body' => json_encode([
                'path' => $path,
                'width' => "1280"
            ], JSON_UNESCAPED_UNICODE),
        ]);
        $imageData = $response->getBody()->getContents();
        return $imageData;
    }
}
